package edu.lingnan.librarymanage.config.web;


import edu.lingnan.librarymanage.core.base.AjaxResult;
import edu.lingnan.librarymanage.core.exception.BizException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 *
 * @author cql
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);


    /**
     * 业务方法-自定义异常
     */
    @ExceptionHandler(BizException.class)
    public AjaxResult handleBizException(BizException e) {
        String message = e.getMessage();
        log.error("出现异常: {}", message);
        return AjaxResult.error(message);
    }

    /**
     * 方法参数校验
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        log.error("{},参数校验异常：{}", e.getMessage(), message);
        return AjaxResult.error(message);
    }


}
